package com.atguigu.campusintelligentassistantsystem.service;

import com.atguigu.campusintelligentassistantsystem.entity.LeaveApply;
import com.atguigu.campusintelligentassistantsystem.entity.LeaveStatus;
import com.atguigu.campusintelligentassistantsystem.repository.LeaveApplyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class LeaveApplyService {

    @Autowired
    private LeaveApplyRepository leaveApplyRepository;

    /**
     * 提交请假申请
     * @param leaveApply 请假信息
     * @return 保存后的请假申请
     */
    public LeaveApply submitLeaveApply(LeaveApply leaveApply) {
        leaveApply.setStatus(LeaveStatus.PENDING); // 默认状态为待审批
        return leaveApplyRepository.save(leaveApply);
    }

    /**
     * 根据ID获取请假申请
     * @param id 请假申请ID
     * @return 请假申请信息
     */
    public LeaveApply getLeaveApplyById(Long id) {
        Optional<LeaveApply> leaveApply = leaveApplyRepository.findById(id);
        return leaveApply.orElse(null);
    }

    /**
     * 根据学生ID获取请假记录
     * @param studentId 学生ID
     * @return 请假记录列表
     */
    public List<LeaveApply> getLeaveAppliesByStudentId(Long studentId) {
        return leaveApplyRepository.findByStudentId(studentId);
    }

    /**
     * 获取所有请假申请
     * @return 请假申请列表
     */
    public List<LeaveApply> getAllLeaveApplies() {
        return leaveApplyRepository.findAll();
    }

    /**
     * 更新请假申请状态
     * @param id 请假申请ID
     * @param status 状态
     * @return 更新后的请假申请
     */
    public LeaveApply updateLeaveApplyStatus(Long id, String status) {
        Optional<LeaveApply> leaveApplyOpt = leaveApplyRepository.findById(id);
        if (leaveApplyOpt.isPresent()) {
            LeaveApply leaveApply = leaveApplyOpt.get();
            // 根据传入的字符串status设置对应的枚举值
            LeaveStatus leaveStatus = LeaveStatus.PENDING;
            switch (status) {
                case "approved":
                    leaveStatus = LeaveStatus.APPROVED;
                    break;
                case "rejected":
                    leaveStatus = LeaveStatus.REJECTED;
                    break;
                case "cancelled":
                    leaveStatus = LeaveStatus.CANCELLED;
                    break;
                default:
                    leaveStatus = LeaveStatus.PENDING;
                    break;
            }
            leaveApply.setStatus(leaveStatus);
            return leaveApplyRepository.save(leaveApply);
        }
        return null;
    }

    /**
     * 删除请假申请
     * @param id 请假申请ID
     */
    public void deleteLeaveApply(Long id) {
        leaveApplyRepository.deleteById(id);
    }
}